package flexconsole.view {
	import flexconsole.AppFacade;
	import flexconsole.ConfigKeys;
	import flexconsole.model.ICategoryProxy;
	import flexconsole.model.IConfigProxy;
	import flexconsole.model.LogLevelModel;
	import flexconsole.view.component.FilterControls;
	
	import flexunit.framework.Assert;
	
	import mx.controls.Tree;
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	/**
	 * Mediator for the FilterControls view.
	 *
	 * @author ivanchoo
	 *
	 */
	public class FilterControlsMediator extends Mediator {
		
		static private var logger:ILogger = Log.getLogger("flexconsole.view.FilterControlsMediator");
		
		private var isViewDirty:Boolean = false;
		
		public function FilterControlsMediator(mediatorName:String = null, viewComponent:Object = null) {
			super(mediatorName, viewComponent);
		}
		
		public function get view():FilterControls {
			return viewComponent as FilterControls;
		}
		
		public function get appFacade():AppFacade {
			return facade as AppFacade;
		}
		
		override public function onRegister():void {
			logger.debug("onRegister()");
			super.onRegister();
			Assert.assertNotNull(appFacade);
			Assert.assertNotNull(view);
			//   Initialize view
			view.resourceBundle = appFacade.resourceBundle;
			view.categoryDataProvider = appFacade.categoryProxy.collection;
			view.logLevelModel = new LogLevelModel();
			updateView();
		}
		
		override public function listNotificationInterests():Array {
			return [ AppFacade.DATA_CHANGE ];
		}
		
		override public function handleNotification(notification:INotification):void {
			switch (notification.getType()) {
				case AppFacade.PROXYNAME_CATEGORY:
				case AppFacade.PROXYNAME_CONFIG:
					invalidateView();
					break;
			}
		}
		
		protected function invalidateView():void {
			if (view && !isViewDirty) {
				isViewDirty = true;
				view.callLater(updateView);
			}
		}
		
		protected function updateView():void {
			logger.debug("updateView()");
			isViewDirty = false;
			var configProxy:IConfigProxy = appFacade.configProxy;
			var categoryProxy:ICategoryProxy = appFacade.categoryProxy;
			//   Update the level checkboxes
			var logLevels:Object = configProxy.getValue(ConfigKeys.FILTER_LOG_LEVELS, null);
			
			if (logLevels) {
				view.logLevelModel.read(logLevels);
			}
			//   Update tree open items
			var tree:Tree = view.category_tree;
			var nodes:XMLList = categoryProxy.source.descendants("*");
			var node:XML;
			
			for each (node in nodes) {
				if (categoryProxy.isOpen(node) != view.isCategoryOpen(node)) {
					view.openCategory(node, categoryProxy.isOpen(node));
				}
			}
		}
	}
}

